/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pessoas.log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Scanner;
import pessoas.interfaces.ILog;

/**
 *
 * @author Bush
 */
public class ConfiguracoesLog {
    private ILog log;
    private String tipoLog;
    private File caminhoLog = new File("src/pessoas/data/configLog.txt");
    private static ConfiguracoesLog instancia;
    private Properties props = new Properties(); 
    
    public ConfiguracoesLog() throws FileNotFoundException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {        
        alteraTipoLog(tipoLogAtual());
    }
    
    public static ConfiguracoesLog getInstancia() throws FileNotFoundException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException{
        if(instancia == null){
            instancia = new ConfiguracoesLog();
        }
        return instancia;
    }
    
    public ILog getLog() {
        return log;
    }

    public String getTipoLog() throws FileNotFoundException {
        return tipoLog = tipoLogAtual();
    }   
        
    private String tipoLogAtual() throws FileNotFoundException{
        Scanner scan = new Scanner(caminhoLog);
        String linha = "";
        while (scan.hasNextLine()) {
            linha += scan.nextLine();
        }
        return linha;
    }
    
    private void alterarTipoLogAtual(String tipo) throws IOException{
        FileWriter w = new FileWriter(caminhoLog, false);
        BufferedWriter bf = new BufferedWriter(w);
        bf.write(tipo);
        bf.close();
    }
    
    public void alteraTipoLog(String tipo) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException{
        Properties prop = getProp();        
        String endClasse = prop.getProperty(tipo);
        Class c = Class.forName(endClasse);
        Object o = c.newInstance();
        log = (ILog) o;
        alterarTipoLogAtual(tipo);
    }   
    
    private Properties getProp() throws IOException {         
        FileInputStream file = new FileInputStream( "src/pessoas/data/configLog.properties"); 
        props.load(file); 
        return props; 
    }
    
    public ArrayList<Object> listaTiposLog() {
        return new ArrayList<Object>(props.keySet());
    }
    
}
